﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace M_FSM
{
    public class M_FSMSystem
    {
        private Dictionary<StateID, M_FSMState> dic = new Dictionary<StateID, M_FSMState>();
        private M_FSMState currentState;
        public void Update()
        {
            currentState?.OnUpdate();
            currentState?.OnReason();
        }
        /// <summary>
        /// 添加状态
        /// </summary>
        /// <param name="state">添加的状态</param>
        /// <returns>是否添加成功</returns>
        public bool AddState(M_FSMState state)
        {
            if (state == null || state.stateID == StateID.Null || dic.ContainsKey(state.stateID))
            {
                return false;
            }
            dic.Add(state.stateID, state);
            return true;
        }
        /// <summary>
        /// 删除状态
        /// </summary>
        /// <param name="state">删除的状态</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteState(M_FSMState state)
        {
            if(state == null)
            {
                return false;
            }
            return DeleteState(state.stateID);
        }
        /// <summary>
        /// 删除状态
        /// </summary>
        /// <param name="stateID">删除的状态</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteState(StateID stateID)
        {
            if (stateID == StateID.Null || !dic.ContainsKey(stateID))
            {
                return false;
            }
            dic.Remove(stateID);
            return true;
        }
        /// <summary>
        /// 转换到下一个状态
        /// </summary>
        /// <param name="transition"></param>
        /// <returns>是否转换成功</returns>
        public bool TransitionState(Transition transition)
        {
            StateID nextStateID = StateID.Null;
            if(transition == Transition.NullTransition || (nextStateID = currentState.GetNextState(transition)) == StateID.Null || !dic.ContainsKey(nextStateID) || currentState == null)
            {
                return false;
            }
            currentState.OnExit();
            currentState = dic[nextStateID];
            currentState.OnEnter();
            return true;
        }
        /// <summary>
        /// 设置FSM启动时第一个状态
        /// </summary>
        /// <param name="state">默认第一个状态</param>
        /// <returns>是否设置成功</returns>
        public bool SetNormalState(M_FSMState state)
        {
            if(state == null || state.stateID == StateID.Null || !dic.ContainsKey(state.stateID))
            {
                return false;
            }
            currentState = state;
            return true;
        }
    }
}
